package com.inspur.gs.sbssdl.sbssgl.yxrj.yxrj.back.bizactions;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.inspur.edp.bef.api.be.IBEManagerContext;
import com.inspur.edp.bef.api.be.IBEService;
import com.inspur.edp.bef.api.be.IBusinessEntity;
import com.inspur.edp.bef.api.lcp.ILcpFactory;
import com.inspur.edp.bef.api.lcp.IStandardLcp;
import com.inspur.edp.bef.api.services.IBefSessionManager;
import com.inspur.edp.bef.engine.entity.AssociationInfo;
import com.inspur.edp.bef.spi.action.AbstractManagerAction;
import com.inspur.edp.cef.entity.changeset.ModifyChangeDetail;
import com.inspur.edp.cef.entity.condition.EntityFilter;
import com.inspur.edp.cef.entity.condition.FilterCondition;
import com.inspur.edp.cef.entity.entity.IEntityData;
import io.iec.edp.caf.commons.utils.SpringBeanUtils;
import lombok.extern.slf4j.Slf4j;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Slf4j
public class sbssYxrjAddRecordMgrAction extends AbstractManagerAction<String> {
    private String Record;

    public sbssYxrjAddRecordMgrAction(IBEManagerContext managerContext, String Record) {
        super(managerContext);
        this.Record = Record;
    }

    @Override
    public void execute() {
        SpringBeanUtils.getBean(IBefSessionManager.class).createSession();
        String yxrjId = "0e7d4ff6-c98f-47b8-98bc-2a96410887dd";
        String sbtsId = "35bf7f5c-48ae-499f-b7f7-2f011a4fb3c8";
        String sbtzId = "efd56b39-0e8d-4441-9fa1-2b019b6fd862";
        ObjectMapper mapper = new ObjectMapper();
        Map<String, Object> map = null;
        try {
//            1.新增设备运行记录
            ILcpFactory iLcpFactory = SpringBeanUtils.getBean(ILcpFactory.class);
            IStandardLcp lcp = iLcpFactory.createLcpByBEId(yxrjId);
            IStandardLcp sbtzLcp = iLcpFactory.createLcpByBEId(sbtzId);
            map = mapper.readValue(Record, Map.class);
            IEntityData data = lcp.retrieveDefault();

            Map<String, Object> sbidMap = (Map<String, Object>) map.get("sbid");
            String sbid = sbidMap.get("sbid").toString();  //当前记录的设备id
            String jlrq = map.get("rq").toString(); //当前记录日期

            //获取设备相关字段信息
            EntityFilter sbfilter = new EntityFilter();
            ArrayList<FilterCondition> sbconditionList = (ArrayList<FilterCondition>) FilterCondition.builder()
                    .andEqual("id", sbid)
                    .build();
            sbfilter.setFilterConditions(sbconditionList);
            List<IEntityData> sbdataList = sbtzLcp.query(sbfilter);
            IEntityData sbData = sbdataList.get(0);

            Object sbbh = sbData.getValue("sbbh");
            Object sbmc = sbData.getValue("sbmc");
            Object sbbhOld = sbData.getValue("sbbh_old");
            Object ggxh = sbData.getValue("ggxh");
            Object xh = sbData.getValue("xh");

            AssociationInfo shopIdInfo = (AssociationInfo) sbData.getValue("shop_id");
            Object shopIdShopName = shopIdInfo.getValue("shop_id_ShopName");

            AssociationInfo zcztInfo = (AssociationInfo) sbData.getValue("zczt");
            Object zcztmc = zcztInfo.getValue("zczt_ztmc");

            AssociationInfo ztInfo = (AssociationInfo) sbData.getValue("zt");
            Object ztmc = ztInfo.getValue("zt_ztmc");

            AssociationInfo abcInfo = (AssociationInfo) sbData.getValue("abc");
            Object abc_lxmc = abcInfo.getValue("abc_lxmc");

            AssociationInfo bmbhInfo = (AssociationInfo) sbData.getValue("bmbh_id");
            Object bmmc = bmbhInfo.getValue("bmbh_id_name");

            AssociationInfo sblbInfo = (AssociationInfo) sbData.getValue("sblb_id");
            Object lbmc = sblbInfo.getValue("sblb_id_lbmc");


            //校验设备每天只能存在一条运行记录
            EntityFilter jlfilter = new EntityFilter();
            ArrayList<FilterCondition> conditionList = (ArrayList<FilterCondition>) FilterCondition.builder()
                    .andEqual("sbid", sbid)
                    .andEqual("rq", jlrq)
                    .build();
            jlfilter.setFilterConditions(conditionList);
            List<IEntityData> jlDataList = lcp.query(jlfilter);
            if (jlDataList.size() > 0) {
                throw new RuntimeException("当前设备已经在" + jlrq + "存在运行记录,请重试");
            }

            ModifyChangeDetail change = new ModifyChangeDetail(data.getID());

            //关联设备
            AssociationInfo sbidinfo = new AssociationInfo();
            sbidinfo.setValue("sbid", sbidMap.get("sbid"));
            change.getPropertyChanges().put("sbid", sbidinfo);

            //存储设备实体字段
            change.getPropertyChanges().put("sbbh", sbbh);
            change.getPropertyChanges().put("sbmc", sbmc);
            change.getPropertyChanges().put("ggxh", ggxh);
            change.getPropertyChanges().put("xh", xh);
            change.getPropertyChanges().put("shopName", shopIdShopName);
            change.getPropertyChanges().put("sbbh_old", sbbhOld);
            change.getPropertyChanges().put("lbmc", lbmc);
            change.getPropertyChanges().put("ztmc", ztmc);
            change.getPropertyChanges().put("zcztmc", zcztmc);
            change.getPropertyChanges().put("abcmc", abc_lxmc);
            change.getPropertyChanges().put("bmmc", bmmc);

            if (map.get("bc") != null) {
                change.getPropertyChanges().put("bc", map.get("bc"));
            }

            AssociationInfo monitorinfo = new AssociationInfo();
            Map<String, Object> monitor = (Map<String, Object>) map.get("monitor");
            monitorinfo.setValue("monitor", monitor.get("monitor"));
            change.getPropertyChanges().put("monitor", monitorinfo);

            AssociationInfo operatorinfo = new AssociationInfo();
            Map<String, Object> operator = (Map<String, Object>) map.get("operator");
            operatorinfo.setValue("operator", operator.get("operator"));
            change.getPropertyChanges().put("operator", operatorinfo);

            //日期
            String rq = map.get("rq").toString();
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            Date date = sdf.parse(rq);
            change.getPropertyChanges().put("rq", date);

            //台时
            BigDecimal yxts = new BigDecimal(map.get("yxts").toString());
            change.getPropertyChanges().put("yxts", yxts);
            BigDecimal gztjts = new BigDecimal(map.get("gztjts").toString());
            change.getPropertyChanges().put("gztjts", gztjts);
            BigDecimal jxbyts = new BigDecimal(map.get("jxbyts").toString());
            change.getPropertyChanges().put("jxbyts", jxbyts);

            if (map.get("bqjljl") != null) {
                change.getPropertyChanges().put("bqjljl", map.get("bqjljl"));
            }
            if (map.get("fhzk") != null) {
                change.getPropertyChanges().put("fhzk", map.get("fhzk"));
            }
            if (map.get("gzjl") != null) {
                change.getPropertyChanges().put("gzjl", map.get("gzjl"));
            }
            if (map.get("jxbyjl") != null) {
                change.getPropertyChanges().put("jxbyjl", map.get("jxbyjl"));
            }
            if (map.get("aqzzzk") != null) {
                change.getPropertyChanges().put("aqzzzk", map.get("aqzzzk"));
            }

            AssociationInfo handoverinfo = new AssociationInfo();
            Map<String, Object> handover = (Map<String, Object>) map.get("handover");
            handoverinfo.setValue("handover", handover.get("handover"));
            change.getPropertyChanges().put("handover", handoverinfo);

            AssociationInfo successorinfo = new AssociationInfo();
            Map<String, Object> successor = (Map<String, Object>) map.get("successor");
            successorinfo.setValue("successor", successor.get("successor"));
            change.getPropertyChanges().put("successor", successorinfo);

            //2.查询对应设备的台时
            IStandardLcp tslcp = iLcpFactory.createLcpByBEId(sbtsId);

            EntityFilter filter = new EntityFilter();
            ArrayList<FilterCondition> conditions = (ArrayList<FilterCondition>) FilterCondition.builder()
                    .andEqual("devId", sbid)
                    .andEqual("rq", jlrq)
                    .build();
            filter.setFilterConditions(conditions);
            List<IEntityData> dataList = tslcp.query(filter);

            List<IEntityData> yxtsList = dataList.stream()
                    .filter(iEntityData -> iEntityData.getValue("type").equals("1"))
                    .collect(Collectors.toList());
            List<IEntityData> gztjtsList = dataList.stream()
                    .filter(iEntityData -> iEntityData.getValue("type").equals("2"))
                    .collect(Collectors.toList());

            if (yxtsList.size() > 1 || gztjtsList.size() > 1) {
                throw new RuntimeException("在" + jlrq + "的设备的台时记录数据有误！");
            }

            //3.新增/更新运行台时记录
            ModifyChangeDetail yxtschange;
            if (yxtsList.size() == 0) { //新增
                IEntityData entityData = tslcp.retrieveDefault();
                yxtschange = new ModifyChangeDetail(entityData.getID());

            } else {  //修改
                String yxtsId = yxtsList.get(0).getValue("ID").toString();
                yxtschange = new ModifyChangeDetail(yxtsId);
            }

            yxtschange.getPropertyChanges().put("devId", sbid);
            yxtschange.getPropertyChanges().put("ts", yxts);
            yxtschange.getPropertyChanges().put("rq", date);
            yxtschange.getPropertyChanges().put("type", "1");

            //4.新增/更新故障停机台时记录
            ModifyChangeDetail gztjtschange;
            if (gztjtsList.size() == 0) { //新增
                IEntityData entityData = tslcp.retrieveDefault();
                gztjtschange = new ModifyChangeDetail(entityData.getID());

            } else {  //修改
                String gztsId = gztjtsList.get(0).getValue("ID").toString();
                gztjtschange = new ModifyChangeDetail(gztsId);
            }

            gztjtschange.getPropertyChanges().put("devId", sbid);
            gztjtschange.getPropertyChanges().put("ts", gztjts);
            gztjtschange.getPropertyChanges().put("rq", date);
            gztjtschange.getPropertyChanges().put("type", "2");

            lcp.modify(change);
            tslcp.modify(yxtschange);
            tslcp.modify(gztjtschange);
            lcp.save();
            tslcp.save();

        } catch (Exception e) {
            throw new RuntimeException(e.getMessage());
        } finally {
            SpringBeanUtils.getBean(IBefSessionManager.class).closeCurrentSession();
        }
    }

    private IBusinessEntity getEntity(String dataId) {
        return (IBusinessEntity) super.getBEManagerContext().getEntity(dataId);
    }

    private IBEService getMgr() {
        return (IBEService) super.getBEManagerContext().getBEManager();
    }
}